import React, { useState, useRef, useEffect, useMemo } from 'react';
import { useModel } from 'umi';
import { PageHeader } from '@ant-design/pro-layout';
import {
  Tag,
  Space,
  Select,
  Collapse,
  Row,
  Col,
  Badge,
  Descriptions,
  TableProps,
  theme,
  Grid,
  Table,
} from 'antd';
import {
  AreaChartOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  DesktopOutlined,
  EditFilled,
  UserOutlined,
} from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
const { Panel } = Collapse;
import ProTable from '@ant-design/pro-table';
import { MyContent } from '@/components/MyUI';
import FlagImage from '@/components/FlagImage';
import TagTags from '@/components/TagTags';
import * as c from '@/services/consts';
import * as api from '@/services/vpnServerMonitor';
import * as utils from '@/utils/utils';
// import * as apiGroup from '@/services/vpnGroup';
import * as apiServer from '@/services/vpnServer';
import NodeGroupForm from './NodeGroupForm';
import NodeForm from './NodeForm';
import NodeAllForm from './NodeAllForm';
import VpnServerForm from '../VpnServer/components/VpnServerForm';
import { ProFormInstance } from '@ant-design/pro-form';
import Countdown from 'antd/lib/statistic/Countdown';
import { CheckCard } from '@ant-design/pro-card';
import moment from 'moment';
import classNames from 'classnames';
import ResizeObserver from 'rc-resize-observer';

const VirtualTable = <RecordType extends object>(props: TableProps<RecordType>) => {
  const { columns, scroll } = props;
  const [tableWidth, setTableWidth] = useState(0);
  const { token } = theme.useToken();

  const widthColumnCount = columns!.filter(({ width }) => !width).length;
  const mergedColumns = columns!.map((column) => {
    if (column.width) {
      return column;
    }

    return {
      ...column,
      width: Math.floor(tableWidth / widthColumnCount),
    };
  });

  const gridRef = useRef<any>();
  const [connectObject] = useState<any>(() => {
    const obj = {};
    Object.defineProperty(obj, 'scrollLeft', {
      get: () => {
        if (gridRef.current) {
          return gridRef.current?.state?.scrollLeft;
        }
        return null;
      },
      set: (scrollLeft: number) => {
        if (gridRef.current) {
          gridRef.current.scrollTo({ scrollLeft });
        }
      },
    });

    return obj;
  });

  const resetVirtualGrid = () => {
    gridRef.current?.resetAfterIndices({
      columnIndex: 0,
      shouldForceUpdate: true,
    });
  };

  useEffect(() => resetVirtualGrid, [tableWidth]);

  const renderVirtualList = (rawData: object[], { scrollbarSize, ref, onScroll }: any) => {
    ref.current = connectObject;
    const totalHeight = rawData.length * 54;

    return (
      <Grid
        ref={gridRef}
        className="virtual-grid"
        columnCount={mergedColumns.length}
        columnWidth={(index: number) => {
          const { width } = mergedColumns[index];
          return totalHeight > scroll!.y! && index === mergedColumns.length - 1
            ? (width as number) - scrollbarSize - 1
            : (width as number);
        }}
        height={scroll!.y as number}
        rowCount={rawData.length}
        rowHeight={() => 54}
        width={tableWidth}
        onScroll={({ scrollLeft }: { scrollLeft: number }) => {
          onScroll({ scrollLeft });
        }}
      >
        {({
          columnIndex,
          rowIndex,
          style,
        }: {
          columnIndex: number;
          rowIndex: number;
          style: React.CSSProperties;
        }) => (
          <div
            className={classNames('virtual-table-cell', {
              'virtual-table-cell-last': columnIndex === mergedColumns.length - 1,
            })}
            style={{
              ...style,
              boxSizing: 'border-box',
              padding: token.padding,
              borderBottom: `${token.lineWidth}px ${token.lineType} ${token.colorSplit}`,
              background: token.colorBgContainer,
            }}
          >
            {(rawData[rowIndex] as any)[(mergedColumns as any)[columnIndex].dataIndex]}
          </div>
        )}
      </Grid>
    );
  };

  return (
    <ResizeObserver
      onResize={({ width }) => {
        setTableWidth(width);
      }}
    >
      <Table
        {...props}
        className="virtual-table"
        columns={mergedColumns}
        pagination={false}
        components={{
          body: renderVirtualList,
        }}
      />
    </ResizeObserver>
  );
};


const VpnGroupTreeList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.VpnServerModel | undefined>(
    undefined,
  );
  // const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
  // const [parent, setParent] = useState<API.VpnGroupModel | undefined>(
  //   undefined,
  // );
  const [productId, setProductId] = useState<string | undefined>(undefined);
  const [totalConnCount, setTotalConnCount] = useState<number>(0);
  const [totalUpload, setTotalUpload] = useState<number | undefined>(0);
  const [totalDownload, setTotalDownload] = useState<number | undefined>(0);
  const [formNodeGroupVisible, setFormNodeGroupVisible] =
    useState<boolean>(false);
  const [formNodeVisible, setFormNodeVisible] = useState<boolean>(false);
  const [formNodeAllVisible, setFormNodeAllVisible] = useState<boolean>(false);
  const [currentNodeGroup, setCurrentNodeGroup] = useState<
    API.VpnGroupMonitorModel | undefined
  >(undefined);
  const [currentNode, setCurrentNode] = useState<
    API.VpnServerMonitorModel | undefined
  >(undefined);
  const [urlGrafanaNode, setUrlGrafanaNode] = useState<string | undefined>(
    undefined,
  );
  const [urlGrafanaNodeGroup, setUrlGrafanaNodeGroup] = useState<
    string | undefined
  >(undefined);
  const [urlGrafanaNodeAll, setUrlGrafanaNodeAll] = useState<
    string | undefined
  >(undefined);

  const [countdownTicks, setCountdownTicks] = useState<number>(
    Date.now() + 30000,
  );
  const [customCountdownTicks, setCustomCountdownTicks] =
    useState<number>(30000);
  const [countdownVisible, setCountdownVisible] = useState<string>('visible');

  const [monitorData, setMonitorData] = useState<API.VpnGroupMonitorModel[]>(
    [],
  );
  // const [reqParams, setReqParams] = useState<any>(undefined);
  // const [reqSorter, setReqSorter] = useState<any>(undefined);
  // const [reqFilter, setReqFilter] = useState<any>(undefined);
  const [controlState, setControlState] = useState<number>(0);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductMenuItems, getSupplier } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductMenuItems: model.getProductMenuItems,
      getSupplier: model.getSupplier,
    }),
  );

  const reload = () => {
    setControlState(new Date().getTime());
    setCountdownTicks(Date.now() + customCountdownTicks);
  };

  const productMenuItems = getProductMenuItems(true);
  const alertGreen = 104857600; //100*1024*1024
  const alertOrange = 209715200; //200*1024*1024
  // const alertRed = 314572800;//300*1024*1024


  const loadDataDo = async () =>
    {
      const result = await api.list(undefined, undefined, undefined);

      if (result && result.success) {
        setTotalConnCount(result.totalConnCount);
        setTotalDownload(result.totalDownload);
        setTotalUpload(result.totalUpload);
        if(result.urlGrafanaNode !=  urlGrafanaNode){
          setUrlGrafanaNode(result.urlGrafanaNode);
          setUrlGrafanaNodeGroup(result.urlGrafanaNodeGroup);
          setUrlGrafanaNodeAll(result.urlGrafanaNodeAll);
        }

        setMonitorData(result.data);
      } else {
        setMonitorData([]);
      }
    };


  useEffect(() => {
    loadDataDo();
  }, [controlState]);

  const handleFormSubmit = async (record: API.VpnServerModel) => {
    let result: API.Result | undefined = undefined;
    if (current) {
      result = await apiServer.update({
        ...current,
        ...record,
      });
    } 

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      reload();
    }
  };

  let columns: ProColumns<API.VpnGroupMonitorModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: (a, b) => (a.status == true ? 1 : 0) - (b.status == true ? 1 : 0),
      valueEnum: {
        true: { status: 'Success' },
        false: { status: 'Error' },
      },
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: (a, b) => (a.parentId ?? '').localeCompare(b.parentId ?? ''),
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '用户等级',
      align: 'center',
      width: 100,
      dataIndex: 'memberLevel',
      sorter: (a, b) => (a.memberLevel ?? 0) - (b.memberLevel ?? 0),
      renderText: (val) => {
        return c.getMemberLevelText(val);
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
      width: 300,
      render: (text, record) => {
        let title = `${text}`;
        if (record.type == c.VpnGroupType.Ghost.value) {
          return (
            <>
              <FlagImage flagName={record.flag} />
              {title}
              <Tag
                color="green"
                style={{
                  marginLeft: 5,
                }}
              >
                {c.getVpnGroupTypeText(record.type)}
              </Tag>
            </>
          );
        }
        return (
          <>
            <FlagImage flagName={record.flag} />
            {title} {record.changeIp > 0 ? <Tag color='blue'>{record.changeIp}分钟</Tag> : ""}
          </>
        );
      },
    },
    {
      title: '服务器',
      align: 'center',
      dataIndex: 'validServerCount',
      width: 150,
      sorter: (a, b) => (a.validServerCount ?? 0) - (b.validServerCount ?? 0),
      renderText: (_, record) => {
        if (record.validServerCount == 0) {
          return (
            <span style={{ color: '#ff4d4f' }}>
              {record.validServerCount}/{record.serverCount}
            </span>
          );
        }
        return `${record.validServerCount}/${record.serverCount}`;
      },
    },
    {
      title: '在线用户',
      dataIndex: 'connCount',
      align: 'center',
      width: 100,
      sorter: (a, b) => (a.connCount ?? 0) - (b.connCount ?? 0),
    },
    {
      title: '下载',
      dataIndex: 'download',
      sorter: (a, b) => (a.download ?? 0) - (b.download ?? 0),
      width: 120,
      render: (_, record) => {
        let val =
          record.download && record.validServerCount > 0
            ? record.download / record.validServerCount
            : 0;
        return (
          <Tag
            color={
              val == 0
                ? ''
                : val <= alertGreen
                ? 'green'
                : val <= alertOrange
                ? 'orange'
                : 'red'
            }
          >
            <b>
              <ArrowDownOutlined /> {c.formatRate(record.download, true)}
            </b>
          </Tag>
        );
      },
    },
    {
      title: '上传',
      dataIndex: 'upload',
      sorter: (a, b) => (a.upload ?? 0) - (b.upload ?? 0),
      width: 150,
      render: (_, record) => {
        let val =
          record.upload && record.validServerCount > 0
            ? record.upload / record.validServerCount
            : 0;
        return (
          <span>
            <Tag
              color={
                val == 0
                  ? ''
                  : val <= alertGreen
                  ? 'green'
                  : val <= alertOrange
                  ? 'orange'
                  : 'red'
              }
            >
              <b>
                <ArrowUpOutlined /> {c.formatRate(record.upload, true)}
              </b>
            </Tag>
            　
            <a
              key="edit"
              onClick={(e) => {
                setFormNodeGroupVisible(true);
                setCurrentNodeGroup(record);
              }}
            >
              <AreaChartOutlined />
            </a>
          </span>
        );
      },
    },
    {
      title: '分组代码',
      dataIndex: 'code',
      width: 100,
      sorter: (a, b) => (a.code ?? '').localeCompare(b.code ?? ''),
    },
    {
      title: '标签',
      dataIndex: 'tags',
      render: (_, record) => <TagTags values={record.tags} />,
    },
    {
      title: '排序',
      align: 'center',
      width: 80,
      dataIndex: 'sort',
      sorter: (a, b) => (a.sort ?? 0) - (b.sort ?? 0),
    },

    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
      sorter: (a, b) => (a.remark ?? '').localeCompare(b.remark ?? ''),
    },
  ];
  

  let childrenColumns: ProColumns<API.VpnServerMonitorModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'status',
      // sorter: true,
      sorter: (a, b) => (a.status == true ? 1 : 0) - (b.status == true ? 1 : 0),
      valueEnum: {
        true: { status: 'Success' },
        false: { status: 'Error' },
      },
    },
    {
      title: '实例ID',
      align: 'center',
      width: 100,
      dataIndex: 'instanceId',
      //sorter: true,
      sorter: (a, b) => a.instanceId - b.instanceId,
    },
    {
      title: '类型',
      align: 'center',
      width: 70,
      dataIndex: 'serverType',
      //sorter: true,
      sorter: (a, b) => (a.serverType ?? 0) - (b.serverType ?? 0),
      render: (_, record) => {
        return c.getServerType(record.serverType)?.label;
      },
    },
    {
      title: '供应商',
      align: 'center',
      width: 100,
      dataIndex: 'supplierId',
      //sorter: true,
      sorter: (a, b) => (a.supplierId ?? 0) - (b.supplierId ?? 0),
      render: (_, record) => {
        return getSupplier(record.supplierId)?.name;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 260,
      sorter: (a, b) => (a.name ?? '').localeCompare(b.name ?? ''),
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      width: 140,
      sorter: (a, b) => (a.ip ?? '').localeCompare(b.ip ?? ''),
    },
    {
      title: '在线',
      align: 'center',
      width: 60,
      dataIndex: 'online',
      sorter: (a, b) => (a.online == true ? 1 : 0) - (b.online == true ? 1 : 0),
      valueEnum: {
        true: { status: 'Success' },
        false: { status: 'Error' },
      },
    },
    {
      title: '在线用户',
      dataIndex: 'connCount',
      align: 'center',
      //sorter: true,
      sorter: (a, b) => (a.connCount ?? 0) - (b.connCount ?? 0),
      width: 100,
    },
    {
      title: '下载',
      align: 'center',
      dataIndex: 'download',
      sorter: (a, b) => (a.download ?? 0) - (b.download ?? 0),
      width: 100,
      render: (_, record) => {
        return (
          <Tag
            color={
              record.download
                ? record.download <= alertGreen
                  ? 'green'
                  : record.download <= alertOrange
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              <ArrowDownOutlined /> {c.formatRate(record.download, true)}
            </b>
          </Tag>
        );
      },
    },
    {
      title: '上传',
      align: 'center',
      dataIndex: 'upload',
      sorter: (a, b) => (a.upload ?? 0) - (b.upload ?? 0),
      width: 150,
      render: (_, record) => {
        return (
          <span>
            <Tag
              color={
                record.upload
                  ? record.upload <= alertGreen
                    ? 'green'
                    : record.upload <= alertOrange
                    ? 'orange'
                    : 'red'
                  : ''
              }
            >
              <b>
                <ArrowUpOutlined /> {c.formatRate(record.upload, true)}
              </b>
            </Tag>
            　
            <a
              key="edit"
              onClick={(e) => {
                setFormNodeVisible(true);
                setCurrentNode(record);
              }}
            >
              <AreaChartOutlined />
            </a>
          </span>
        );
      },
    },
    {
      title: 'CPU',
      align: 'center',
      dataIndex: 'cpuUsed',
      width: 100,
      sorter: (a, b) => (a.cpuUsed ?? 0) - (b.cpuUsed ?? 0),
      render: (_, record) => {
        return (
          <Tag
            color={
              record.cpuUsed
                ? record.cpuUsed < 0.5
                  ? 'green'
                  : record.cpuUsed < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {record.cpuCore} / {c.formatPercentage(record.cpuUsed, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '内存',
      dataIndex: 'memUsedPer',
      align: 'center',
      width: 120,
      sorter: (a, b) => (a.memUsedPer ?? 0) - (b.memUsedPer ?? 0),
      render: (_, record) => {
        // let usePer = 0;
        // if (record.memAvl && record.memTotal && record.memTotal > 0) {
        //   usePer = (record.memTotal - record.memAvl) / record.memTotal;
        // }
        let usedPer = record.memUsedPer ?? 0;
        return (
          <Tag
            color={
              usedPer != 0
                ? usedPer < 0.5
                  ? 'green'
                  : usedPer < 0.9
                  ? 'orange'
                  : 'red'
                : ''
            }
          >
            <b>
              {c.formatRate(record.memTotal, true)} /{' '}
              {c.formatPercentage(usedPer, 1)}%
            </b>
          </Tag>
        );
      },
    },
    {
      title: '版本',
      dataIndex: 'version',
      align: 'center',
      width: 70,
      sorter: (a, b) => (a.version ?? '').localeCompare(b.version ?? ''),
    },
    {
      title: '启动时间',
      align: 'center',
      dataIndex: 'startTime',
      sorter: (a, b) =>
        utils
          .formatUtcToLocal(a.startTime)
          .localeCompare(utils.formatUtcToLocal(b.startTime)),
      width: 160,
      render: (_, record) => utils.formatUtcToLocal(record.startTime),
    },
    {
      title: '运行时长',
      align: 'center',
      dataIndex: 'runSeconds',
      sorter: (a, b) =>
        utils
          .formatDuration(a.runSeconds)
          .localeCompare(utils.formatDuration(b.runSeconds)),
      width: 150,
      render: (_, record) =>
        record.runSeconds > 0 ? utils.formatDuration(record.runSeconds) : '',
    },
    {
      title: '带宽限制',
      align: 'center',
      dataIndex: 'maxBandwidth',
      width: 90,
      sorter: (a, b) => (a.maxBandwidth ?? 0) - (b.maxBandwidth ?? 0),
      render: (text) => ((text as number) > 0 ? text : ''),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      sorter: (a, b) => (a.remark ?? '').localeCompare(b.remark ?? ''),
      ellipsis: true,
    },
  ];

  childrenColumns = childrenColumns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 50,
      render: (_, record) => {
        let cmps = [];

        if (hasRight('vpnserver_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <MyContent>
{
              // if(item.type == 2) return <></>;
              // let reportColor = item.reportStatus == 1 ? "success" : "error";
              // let statChErr = item.statChErr ? item.statChErr : 0;
              // let statChOk = item.statChOk ? item.statChOk : 0;
              // let memUsedPer = 0;
              // if(item.memTotal){
              //   memUsedPer = 1- (item.memUsed ?? 0) / item.memTotal;
              // }
              // let m50 = 52428800;
              // let m100 = 104857600;
              // let netRAlert = -1;
              // if(item.networkReceive){
              //   if(item.networkReceive < m50){
              //     netRAlert = 0;
              //   }
              //   else if(item.networkReceive < m100){
              //     netRAlert = 1;
              //   }
              //   else{
              //     netRAlert = 2;
              //   }
              // }
              // let netTAlert = -1;
              // if(item.networkTransmit){
              //   if(item.networkTransmit < m50){
              //     netTAlert = 0;
              //   }
              //   else if(item.networkTransmit < m100){
              //     netTAlert = 1;
              //   }
              //   else{
              //     netTAlert = 2;
              //   }
              // }
}
        <PageHeader ghost={false} title="" subTitle="" 
        // extra={
        //   <>
        //   <Space
        //     style={{
        //       marginRight: '0px',
        //     }}
        //   >
        //     <span>
        //       <Countdown
        //         title=""
        //         key="cdRefresh"
        //         value={countdownTicks}
        //         format="s"
        //         prefix=""
        //         suffix="秒后刷新"
        //         valueStyle={{
        //           fontSize: 14,
        //           color: 'gray',
        //         }}
        //         style={{ visibility: countdownVisible }}
        //         onFinish={reload}
        //       />
        //     </span>
        //     <span>
        //       <Select
        //         defaultValue={30}
        //         style={{ width: 80 }}
        //         options={[
        //           {
        //             label: '禁止',
        //             value: 0,
        //           },
        //           {
        //             label: '15秒',
        //             value: 15,
        //           },
        //           {
        //             label: '20秒',
        //             value: 20,
        //           },
        //           {
        //             label: '30秒',
        //             value: 30,
        //           },
        //           {
        //             label: '60秒',
        //             value: 60,
        //           },
        //           {
        //             label: '120秒',
        //             value: 120,
        //           },
        //         ]}
        //         onChange={(val) => {
        //           if (val == 0) {
        //             setCountdownVisible('hidden');
        //             setCountdownTicks(-1);
        //           } else {
        //             if (countdownVisible == 'hidden') {
        //               setCountdownVisible('visible');
        //               setCountdownTicks(Date.now() + val * 1000);
        //               actionRef.current?.reload();
        //             } else {
        //               setCustomCountdownTicks(val * 1000);
        //               setCountdownTicks(Date.now() + val * 1000);
        //               actionRef.current?.reload();
        //             }
        //           }
        //         }}
        //       />
        //     </span>

        //     <span>
        //       流量：
        //       <Tag color="red"><b><ArrowDownOutlined /> {c.formatRate(totalDownload, true)}</b></Tag>
        //       <Tag color="green"><b><ArrowUpOutlined /> {c.formatRate(totalUpload, true)}</b></Tag>
        //       <a onClick={(e) => {
        //           setFormNodeAllVisible(true);
        //         }}
        //       ><AreaChartOutlined /></a>
        //     </span>
        //     <span>
        //       在线用户：<Tag color="red"><b>{totalConnCount}</b></Tag>
        //     </span>
        //   </Space>
        // </>
        // }
        >
        <Collapse style={{marginBottom:25}}>
          {monitorData?.map((group)=>{
            return ;
            let groupDLAvg = group.download && group.validServerCount > 0 ? group.download / group.validServerCount : 0;
            let groupULAvg = group.upload && group.validServerCount > 0 ? group.upload / group.validServerCount : 0;
return(
          <Panel key={`group_${group.id}`} 
            header={<Row gutter={24}>
              <Col style={{width:30}}>{group.status ? <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} /> : <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />}</Col>
              <Col style={{width:100}}>{group.productId ? getProduct(group.productId)?.name : ""}</Col>
              <Col style={{width:70}}>{c.getMemberLevelText(group.memberLevel)}</Col>
              <Col style={{width:100}}>{group.code}</Col>
              <Col style={{width:300}}>{
                group.type == c.VpnGroupType.Ghost.value ?
                  (<><FlagImage flagName={group.flag} />
                      {group.name}
                      <Tag color="green" style={{ marginLeft: 5,}}>
                        {c.getVpnGroupTypeText(group.type)}
                      </Tag>
                    </>)
                :
                (<><FlagImage flagName={group.flag} />
                    {group.name} {group.changeIp > 0 ? <Tag color='blue'>{group.changeIp}分钟</Tag> : ""}
                  </>)
              }</Col>
              <Col style={{width:150}}><DesktopOutlined style={{color:"#999999"}} /> {
                  group.validServerCount == 0 ? <span style={{ color: '#ff4d4f' }}>{group.validServerCount}/{group.serverCount}</span>
                    : `${group.validServerCount}/${group.serverCount}`
              }</Col>
              <Col style={{width:150}}><UserOutlined style={{color:"#999999"}} /> {group.connCount}</Col>
              <Col style={{width:100}}>{
                <Tag color={groupDLAvg == 0 ? '' : groupDLAvg <= alertGreen ? 'green' : groupDLAvg <= alertOrange ? 'orange' : 'red' }>
                <b><ArrowDownOutlined /> {c.formatRate(group.download, true)}</b>
                </Tag>
              }</Col>
              <Col style={{width:150}}>{<>
                <Tag color={groupULAvg == 0 ? '' : groupULAvg <= alertGreen ? 'green' : groupULAvg <= alertOrange ? 'orange' : 'red' }>
                <b><ArrowUpOutlined /> {c.formatRate(group.upload, true)}</b>
                </Tag>
                <a onClick={(e) => {
                  setFormNodeGroupVisible(true);
                  setCurrentNodeGroup(group);
                }}><AreaChartOutlined /></a>
                </>
              }</Col>
              <Col><TagTags values={group.tags} /></Col>
              <Col>{group.remark}</Col>              
            </Row>}
          >

            
            <ProTable
              columns={childrenColumns}
              headerTitle={false}
              search={false}
              options={false}
              pagination={false}
              dataSource={group.data}
              tableStyle={{ marginLeft: 10 }}
            />

                  {/* <Descriptions size="small" column={1}>
                    {
             group.data.map((item)=>{
              
              let usedMemPer = item.memUsedPer ?? 0;
              return (<Descriptions.Item label="">                  
              <Row>
              <Col style={{width:30}}>{item.status ? <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} /> : <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />}</Col>
              <Col style={{width:70}}>{item.instanceId}</Col>
              <Col style={{width:70}}>{c.getServerType(item.serverType)?.label}</Col>
              <Col style={{width:150}}>{getSupplier(item.supplierId)?.name}</Col>
              <Col style={{width:300}}>
                 {item.name}
                <a onClick={(e) => {
                  setFormVisible(true);
                  setCurrent(record);
                }}
                ><EditFilled /></a></Col>
              <Col style={{width:150}}>{item.ip}</Col>
              <Col style={{width:30}}>{item.online == true ? <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} /> : <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />}</Col>
              <Col style={{width:100}}><UserOutlined style={{color:"#999999"}} /> {item.connCount}</Col>
              <Col style={{width:100}}>{
                <Tag color={!item.download || item.download == 0 ? '' : item.download <= alertGreen ? 'green' : item.download <= alertOrange ? 'orange' : 'red' }>
                <b><ArrowDownOutlined /> {c.formatRate(item.download, true)}</b>
                </Tag>
              }</Col>
              <Col style={{width:150}}>{<>
                <Tag color={!item.upload || item.upload == 0 ? '' : item.upload <= alertGreen ? 'green' : item.upload <= alertOrange ? 'orange' : 'red' }>
                <b><ArrowUpOutlined /> {c.formatRate(item.upload, true)}</b>
                </Tag>
                <a onClick={(e) => {
                setFormNodeVisible(true);
                setCurrentNode(item);
                }}><AreaChartOutlined /></a>
                </>
              }</Col>
              <Col style={{width:140}}>
                <span style={{color:"#999999"}}>CPU</span> <Tag color={item.cpuUsed ? item.cpuUsed < 0.5 ? 'green' : item.cpuUsed < 0.9 ? 'orange' : 'red' : '' }>
                <b>{item.cpuCore} / {c.formatPercentage(item.cpuUsed, 1)}%</b>
                </Tag>
              </Col>
              <Col style={{width:150}}>
                <span style={{color:"#999999"}}>内存</span> <Tag color={usedMemPer != 0 ? usedMemPer < 0.5 ? 'green' : usedMemPer < 0.9 ? 'orange' : 'red' : '' }>
                <b>{c.formatRate(item.memTotal, true)} / {c.formatPercentage(usedMemPer, 1)}%</b>
                </Tag>
              </Col>
              <Col style={{width:50}}>{item.version}</Col>
              <Col style={{width:150}}>{utils.formatUtcToLocal(item.startTime)}</Col>
              <Col style={{width:80}}>{utils.formatDuration(item.runSeconds)}</Col>
              <Col style={{width:100}}>{item.maxBandwidth > 0 ? <><span style={{color:"#999999"}}>带宽</span> {item.maxBandwidth}<span style={{color:"#999999"}}>MB</span></> : ''}</Col>
              <Col style={{width:100}}>{item.remark}</Col>
            </Row>
                  
                  </Descriptions.Item>);
                  
            })
            }
                  </Descriptions> */}



          {/* <CheckCard.Group key={`check_card_group_${group.id}`} style={{margin:0}} 
          // multiple={true} value={selectApps} 
          // onChange={(checkValue)=>{
          //   console.log(checkValue);
          //   // setSelectApps(checkValue);
          //   if(checkValue){
          //     formRef.current?.setFieldsValue({filterApp:[checkValue]})
          //   }
          //   else{
          //     formRef.current?.setFieldsValue({filterApp:[]})
          //   }
          //   //filterData();
          //   setControlState(new Date().getTime());
          // }}
          >
              {group.data?.map((item)=>{
                let memUsedPer = item.memUsedPer ?? 0;


              return (<CheckCard style={{width:225, paddingRight:0}}  extra={<a
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(item);
              }}
            >
              <EditFilled />
            </a>}
              title={<><div style={{color:"#777"}}>
               {item.name}_{item.id}
                </div>
                </>} 
              // extra={statChErr == 0 && statChOk == 0 ? "" :
              //   <><div style={{verticalAlign:'top',height:40,}}><b style={{marginLeft: 10,color: statChErr > 0 ? "red" : "#777"}}>{statChErr}</b>/<b style={{color: statChOk > 0 ? "blue" : "#aaa"}}>{statChOk}</b></div></>}
              value={item.id} description={<>

                  汇报<Space><Tag color={reportColor} style={{ width:160,marginLeft:3,marginRight:0}}>
                    {item.reportTime ? moment(item.reportTime).format("YY-MM-DD HH:mm:ss") : "N/A"}
                  <span style={{color:"#999", marginLeft:6}}>{item.version ? "v" +item.version : "N/A"}</span>
                  </Tag></Space> 

                CPU<Space><Tag style={{ width:160,marginLeft:4,marginRight:0}} color={item.cpuUsed ? item.cpuUsed < 0.5 ? "green" : item.cpuUsed < 0.7 ? "gold" : item.cpuUsed < 0.9 ? "orange" : "red" : ""}>
                {item.cpuCore} / {c.formatPercentage(item.cpuUsed, 1)}%　{item.startTime ? moment(item.startTime).format("YY-MM-DD HH:mm:ss") : "N/A"}
                  </Tag></Space>
                内存<Space><Tag style={{ width:160,marginLeft:3,marginRight:0}} color={memUsedPer == 0 ? "" : memUsedPer < 0.5 ? "green" : memUsedPer < 0.7 ? "gold" :memUsedPer < 0.9 ? "orange" : "red"}>
                {item.memTotal ? `${c.formatRate(item.memTotal, true)} / ${c.formatPercentage(memUsedPer, 1)}%` : "N/A"}
                  </Tag></Space>
                
                网络<Space><Tag style={{ width:160,marginLeft:3,marginRight:0}} color={ netRAlert == 2 || netTAlert == 2 ? "red" : netRAlert == 1 || netTAlert == 1 ? "orange" : netRAlert == 0 || netTAlert == 0 ? "green" : ""}>
                {item.networkReceive ? 
                <span style={{fontWeight:netRAlert < 1 ? 'normal': 'bold'}}>R:{formatRate(item.networkReceive, true)}</span> : "R:N/A"} / {item.networkTransmit ? 
                <span style={{fontWeight:netTAlert < 1 ? 'normal': 'bold'}}>T:{formatRate(item.networkTransmit, true)}</span> : "T:N/A"}
                  </Tag></Space> 
                  
                  IP<Space><Tag style={{ width:160,marginLeft:19,marginRight:0}}>
                   {item.ip ? item.ip : "N/A"}
                  </Tag></Space>




              </>} />)
              })}
          </CheckCard.Group> */}
          

          </Panel>
)
            })}
        </Collapse>
        </PageHeader>




      <ProTable<API.VpnGroupMonitorModel>
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        components= {
          {
            // body:{
            //   cell:(props) => {
            //     const { onMouseEnter, onMouseLeave, ...restProps } = props;
            //     // console.log(restProps);
            //     return <td key={restProps?.key}  {...restProps} />;
            //   },
            //   row:(props) => {
            //     const { onMouseEnter, onMouseLeave, ...restProps } = props;
            //     // console.log(restProps);
            //     return <tr key={restProps?.key} {...restProps} />;
            //   }
            // }
          }
          // useMemo(() => {
          //   return () => {
          //     body:{cell:(props) => {
          //     const { onMouseEnter, onMouseLeave, ...restProps } = props;
          //     return <td key={restProps?.key} {...restProps} />;
          //   }}
          //   };
          // }, [])
        }
        expandable={{
          // expandedRowRender: (record) => (
          //   // <ProTable
          //   //   columns={childrenColumns}
          //   //   headerTitle={false}
          //   //   search={false}
          //   //   options={false}
          //   //   pagination={false}
          //   //   dataSource={record.data}
          //   //   tableStyle={{ marginLeft: 10 }}
          //   //   components= {
          //   //     {
          //   //       body:{
          //   //         cell:(props) => {
          //   //           const { onMouseEnter, onMouseLeave, ...restProps } = props;
          //   //           // console.log(props);
          //   //           return <td key={restProps?.key}  {...restProps} />;
          //   //         },
          //   //         row:(props) => {
          //   //           const { onMouseEnter, onMouseLeave, ...restProps } = props;
          //   //           // console.log(restProps);
          //   //           return <tr key={restProps?.key} {...restProps} />;
          //   //         }
          //   //       }
          //   //     }
          //   //     // useMemo(() => {
          //   //     //   return () => {
          //   //     //     body:{cell:(props) => {
          //   //     //     const { onMouseEnter, onMouseLeave, ...restProps } = props;
          //   //     //     return <td key={restProps?.key} {...restProps} />;
          //   //     //   }}
          //   //     //   };
          //   //     // }, [])
          //   //   }
          //   // />

          // ),
          defaultExpandedRowKeys: ['0'],
        }}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                }}
              >
                <span>
                  <Countdown
                    title=""
                    key="cdRefresh"
                    value={countdownTicks}
                    format="s"
                    prefix=""
                    suffix="秒后刷新"
                    valueStyle={{
                      fontSize: 14,
                      color: 'gray',
                    }}
                    style={{ visibility: countdownVisible }}
                    onFinish={reload}
                  />
                </span>
                <span>
                  <Select
                    defaultValue={30}
                    style={{ width: 80 }}
                    options={[
                      {
                        label: '禁止',
                        value: 0,
                      },
                      {
                        label: '15秒',
                        value: 15,
                      },
                      {
                        label: '20秒',
                        value: 20,
                      },
                      {
                        label: '30秒',
                        value: 30,
                      },
                      {
                        label: '60秒',
                        value: 60,
                      },
                      {
                        label: '120秒',
                        value: 120,
                      },
                    ]}
                    onChange={(val) => {
                      if (val == 0) {
                        setCountdownVisible('hidden');
                        setCountdownTicks(-1);
                      } else {
                        if (countdownVisible == 'hidden') {
                          setCountdownVisible('visible');
                          setCountdownTicks(Date.now() + val * 1000);
                          actionRef.current?.reload();
                        } else {
                          setCustomCountdownTicks(val * 1000);
                          setCountdownTicks(Date.now() + val * 1000);
                          actionRef.current?.reload();
                        }
                      }
                    }}
                  />
                </span>

                <span>
                  流量：
                  <Tag color="red">
                    <b>
                      <ArrowDownOutlined /> {c.formatRate(totalDownload, true)}
                    </b>
                  </Tag>
                  <Tag color="green">
                    <b>
                      <ArrowUpOutlined /> {c.formatRate(totalUpload, true)}
                    </b>
                  </Tag>
                  <a
                    key="edit"
                    onClick={(e) => {
                      setFormNodeAllVisible(true);
                    }}
                  >
                    <AreaChartOutlined />
                  </a>
                </span>

                <span>
                  在线用户：<Tag color="#87d068">{totalConnCount}</Tag>
                </span>
              </Space>
            </>
          ),
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              setProductId(tabKey as string);
            },
          },
        }}
        toolBarRender={() => {
          // if (hasRight('tag_create')) {
          //   return [
          //     <Button
          //       type="primary"
          //       key="create"
          //       onClick={() => {
          //         setFormVisible(true);
          //       }}
          //     >
          //       <PlusOutlined /> 新建
          //     </Button>,
          //   ];
          // }
          return [];
        }}
        columns={columns}
        // params={{
        //   productId:
        //     productId && productId !== c.DefaultOptionAll.key
        //       ? parseInt(productId)
        //       : undefined,
        // }}
        // request={async (
        //   params: { [key: string]: any },
        //   sorter?: { [key: string]: any },
        //   filter?: { [key: string]: any },
        // ) => {
        //   // console.log(params,sorter,filter);
        //   setReqParams(params);
        //   setReqSorter(sorter);
        //   setReqFilter(filter);
        //   setControlState(new Date().getTime());
        //   return [];
        // }}
        dataSource={monitorData}
      />

      <VpnServerForm
        visible={formVisible}
        defaultGroupIds={undefined}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
      <NodeGroupForm
        visible={formNodeGroupVisible}
        current={currentNodeGroup}
        urlGrafana={urlGrafanaNodeGroup}
        onCancel={() => {
          setFormNodeGroupVisible(false);
          setCurrentNodeGroup(undefined);
        }}
      />
      <NodeForm
        visible={formNodeVisible}
        current={currentNode}
        urlGrafana={urlGrafanaNode}
        onCancel={() => {
          setFormNodeVisible(false);
          setCurrentNode(undefined);
        }}
      />
      <NodeAllForm
        visible={formNodeAllVisible}
        urlGrafana={urlGrafanaNodeAll}
        onCancel={() => {
          setFormNodeAllVisible(false);
        }}
      />
    </MyContent>
  );
};

export default VpnGroupTreeList;
